package com.lzy.mall.search.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.lzy.mall.search.config.ElasticConfig;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author lzy
 * @date 2021/9/6 11:16
 */
@RestController
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TestController {

    private final RestHighLevelClient client;

    @GetMapping("/search")
    public String search(){
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("newbank");
        //指定DSL，检索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //1.1 构造检索条件
        builder.query(QueryBuilders.matchQuery("address","Lane"));

        //1.2 按照年龄聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        builder.aggregation(ageAgg);

        //1.3 计算平均薪资
        AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
        builder.aggregation(balanceAvg);
//        builder.size(0);
        System.out.println("检索条件：" + builder.toString());

        searchRequest.source(builder);

        //2.执行检索
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (IOException e) {
        }
        //3.分析结果
        System.out.println(searchResponse.toString());
        //3.1 获取所有查到的数据
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // json字符串，可以直接转成bean对象
            String sourceAsString = hit.getSourceAsString();
//            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        }

        //3.2 获取这次聚合检索到的分析结果
        Aggregations aggregations = searchResponse.getAggregations();

        Terms age = aggregations.get("ageAgg");
        List<? extends Terms.Bucket> buckets = age.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            //"buckets" : [
            //        {
            //          "key" : 29,
            //          "doc_count" : 2
            //        },
            //        {
            //          "key" : 31,
            //          "doc_count" : 2
            //        }
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
        }

        //"balanceAvg" : {
        //      "value" : 37133.625
        //    }
        Avg balance = aggregations.get("balanceAvg");
        //平均薪资
        balance.getValue();

        return searchResponse.toString();
    }

    @GetMapping("/index")
    public String index(){
        IndexRequest indexRequest = new IndexRequest("users");
        indexRequest.id("1");
        User user = new User();
        user.setAge(50);
        user.setUserName("lzy");
        JSONObject jsonObject = new JSONObject(user);
        String jsonStr = JSONUtil.toJsonStr(user);
        String s = JSON.toJSONString(user);

        //设置要保存的内容，指定的数据和类型
        indexRequest.source(s, XContentType.JSON);

        //执行创建索引和保存数据
        IndexResponse index = null;
        try {
            index = client.index(indexRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            System.out.println("----------------------");
        }
        System.out.println(index);

        return index.toString();
    }


    @GetMapping("/test")
    public String test(){
        return "test";
    }

    class User{
        private String userName;
        private Integer age;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }
}
